package permission

import (
	"context"
	"fmt"
	"private-domain-overseas-service/admin/business/api/internal/repository/permission"
	"private-domain-overseas-service/pkg/common"
	"private-domain-overseas-service/pkg/status/bizadmin"
	"private-domain-overseas-service/pkg/xerr"
	"private-domain-overseas-service/tools/ent/adminuser"
	"private-domain-overseas-service/tools/ent/predicate"

	"private-domain-overseas-service/admin/business/api/internal/svc"
	"private-domain-overseas-service/admin/business/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type AdminUserInfoEditLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewAdminUserInfoEditLogic - 编辑用户信息
func NewAdminUserInfoEditLogic(ctx context.Context, svcCtx *svc.ServiceContext) *AdminUserInfoEditLogic {
	return &AdminUserInfoEditLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *AdminUserInfoEditLogic) AdminUserInfoEdit(req *types.AdminUserInfoEditResponse) error {
	userDao := permission.NewAdminUserDao(l.ctx, l.svcCtx)

	userId := common.JwtAdminAuthUserId(l.ctx)
	if userId < 0 {
		return xerr.ErrCodeMsg(xerr.ServerAdminUserNotLogin, "用户未登录")
	}

	// 查询用户信息
	adminUserCond := make([]predicate.AdminUser, 0, 2)
	adminUserCond = append(adminUserCond, adminuser.IDEQ(int(userId)))
	adminUserCond = append(adminUserCond, adminuser.IsDeleteEQ(bizadmin.NotDelete))
	adminUser, err := userDao.AdminUserFirst(adminUserCond)
	if adminUser == nil || err != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("查询用户失败：%v", err.Error()))
	}
	// 检查状态
	if adminUser.AdminUserStatus == bizadmin.StatusDisable {
		return xerr.ErrCodeMsg(xerr.ServerAdminAccountBanned, "用户已被禁用，无法修改信息")
	}

	// 更新用户信息
	if req.NickName != "" {
		adminUser.AdminUserNickname = req.NickName
	}
	if req.Email != "" {
		adminUser.AdminUserEmail = req.Email
	}
	err = userDao.AdminUserUpdate(adminUser, nil)
	if err != nil {
		return xerr.ErrCodeMsg(xerr.ServerOperationExceptionError, fmt.Sprintf("更新用户信息失败：%v", err.Error()))
	}

	return nil
}
